package com.youi.web;

import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import com.alibaba.fastjson.JSONObject;
import com.youi.common.Common;
import com.youi.common.DelStatus;
import com.youi.common.SessionKey;
import com.youi.entity.Refundorder;
import com.youi.entity.Sysuser;
import com.youi.entity.Userorder;
import com.youi.entity.Yibaodivide;
import com.youi.entity.Yibaopayment;
import com.youi.entity.Yibaorefund;
import com.youi.entity.vo.ExportRefundOrderVO;
import com.youi.exception.BusinessException;
import com.youi.manage.HttpRequestManage;
import com.youi.manage.HttpSessionManage;
import com.youi.service.OrdergoodsService;
import com.youi.service.RefundorderService;
import com.youi.service.UserorderService;
import com.youi.service.YibaodivideService;
import com.youi.service.YibaopaymentService;
import com.youi.service.YibaorefundService;
import com.youi.third.yibaopay.YibaopayUtil;
import com.youi.third.yibaopay.model.Divideresult;
import com.youi.third.yibaopay.model.Refundresult;
import com.youi.util.CommonInfoUtil;
import com.youi.util.DateUtil;
import com.youi.util.EasyPoiUtil;
import com.youi.util.ExcelStyleUtil;
import com.youi.util.JsonUtil;
import com.youi.util.ObjectUtil;
import com.youi.util.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.ParseException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 退款订单控制层
 *
 * @author Administrator
 */
@Controller
public class RefundorderController extends HttpRequestManage {

    @Autowired
    private RefundorderService refundorderService;
    @Autowired
    private OrdergoodsService ordergoodsService;
    @Autowired
    private YibaopaymentService yibaopaymentService;
    @Autowired
    private UserorderService userorderService;
    @Autowired
    private YibaorefundService yibaorefundService;
    @Autowired
    private YibaodivideService yibaodivideService;


    /**
     * I-83
     * 查询退款订单
     *
     * @throws IOException
     */
    @ResponseBody
    @RequestMapping("sysUserGetInfo/getRefundorder")
    public String getRefundorder(ModelMap modelMap, HttpServletRequest request) throws BusinessException, ParseException, IOException {
        Sysuser sysuser = (Sysuser) HttpSessionManage.getAttribute(request, SessionKey.SYSUSER);
        Integer pageIndex = optInteger("pageIndex", request, 1);
        Integer pageNum = optInteger("pageNum", request, 10);
        String des = optString("des", request, Common.DESC);
        String pms = optString("pms", request);
        String phone = optString("phone", request);
        String refundOrderNo = optString("refundOrderNo", request);
        String orderNo = optString("orderNo", request);
        Integer status = optInteger(Common.STATUS, request);
        Integer applyStatus = optInteger("applyStatus", request);
        String goodsPms = optString("goodsPms", request);
        String start = optString("start", request);
        String end = optString("end", request);
        String applyStart = optString("applyStart", request);
        String applyEnd = optString("applyEnd", request);
        Map<String, Object> prams = new HashMap<String, Object>();
        prams.put(Common.DELSTATUS, DelStatus.NODEL);
        prams.put("orderType", 1);
        if (sysuser.getMerchantId() != null) {
            prams.put("merchantId", sysuser.getMerchantId());
        }
        //退款状态
        if (status != null) {
            prams.put(Common.STATUS, status);
        }
        //审核状态
        if (applyStatus != null) {
            prams.put("applyStatus", applyStatus);
        }
        //退款订单号
        if (refundOrderNo != null && refundOrderNo.length() > 0) {
            prams.put("refundOrderNo", refundOrderNo);
        }
        //原订单号
        if (orderNo != null && orderNo.length() > 0) {
            prams.put("orderNo", orderNo);
        }
        //商品金额、商品编码
        if (goodsPms != null && goodsPms.length() > 0) {
            List<String> orderNoList = ordergoodsService.getGoodsIdList(goodsPms);
            if (orderNoList != null && orderNoList.size() > 0) {
                prams.put("orderNo", orderNoList);
            }
        }
        //手机号
        if (phone != null && phone.length() > 0) {
            prams.put("phone", phone);
        }
        Map<String, Object> sortPram = new HashMap<String, Object>();
        sortPram.put(Common.ID, des);
        Map<String, Object> searchPram = null;
        if (pms != null) {
            searchPram = new HashMap<String, Object>();
        }
        Map<String, Object> startTime = null;
        if (start != null || applyStart != null) {
            startTime = new HashMap<String, Object>();
            if (start != null) {
                startTime.put(Common.GMTCREATED, DateUtil.simpdfyMdHms.parse(start));
            }
            if (applyStart != null) {
                startTime.put("gmtApply", DateUtil.simpdfyMdHms.parse(applyStart));
            }
        }
        Map<String, Object> endTime = null;
        if (end != null || applyEnd != null) {
            endTime = new HashMap<String, Object>();
            if (end != null) {
                endTime.put(Common.GMTCREATED, DateUtil.simpdfyMdHms.parse(end));
            }
            if (applyEnd != null) {
                endTime.put("gmtApply", DateUtil.simpdfyMdHms.parse(applyEnd));
            }
        }
        List<Refundorder> refundorderList = refundorderService.getByParamsList(prams, searchPram, sortPram, (pageIndex - 1) * pageNum, pageNum, startTime, endTime);
        if (refundorderList == null || refundorderList.size() == 0) {
            return JsonUtil.toJson(CommonInfoUtil.NULLDATA, "空数据");
        }
        Integer pageCount = refundorderService.getCountByParamss(prams, searchPram, startTime, endTime);
        modelMap.put(CommonInfoUtil.PAGECOUNT, Page.getCount(pageCount, pageNum));//pageCount  总页数
        modelMap.put(CommonInfoUtil.PAGEINDEX, pageIndex);            //pageIndex     查询页数
        modelMap.put(CommonInfoUtil.ALLCOUINT, pageCount);
        modelMap.put(CommonInfoUtil.DATA, refundorderList);        //jsonObjectList json对象集合
        refundorderService.getRefundorderMsg(refundorderList);
        return JsonUtil.toJson(CommonInfoUtil.SUCCESS, "操作完成", modelMap);
    }

    /**
     * I-84
     * 查询退款订单详情
     *
     * @throws IOException
     */
    @ResponseBody
    @RequestMapping("sysUserGetInfo/getRefundorderById")
    public String getRefundorderById(ModelMap modelMap, HttpServletRequest request) throws BusinessException, IOException {
        Long id = getLong("id", request);
        Refundorder refundorder = refundorderService.get(id);
        if (refundorder == null) {
            return JsonUtil.toJson(CommonInfoUtil.NULLDATA, "空数据");
        }
        refundorderService.getRefundorderMsg(refundorder);
        return JsonUtil.toJson(CommonInfoUtil.SUCCESS, "操作完成", refundorder);//jsonObject	json对象
    }

    /**
     * I-85
     * 审核退款订单
     */
    @ResponseBody
    @RequestMapping("sysUserGetInfo/applyRefundorder")
    public String applyRefundorder(ModelMap modelMap, HttpServletRequest request) throws BusinessException {
        String ids = getString("ids", request);
        Integer applyStatus = getInteger("applyStatus", request);
        String reason = optString("reason", request);
        List<Long> idsList = ObjectUtil.getIdListByIds(ids);
        if (idsList == null || idsList.size() == 0) {
            return JsonUtil.toJson(CommonInfoUtil.PARAMERROR, "ids参数错误");
        }
        Map<String, Object> params = new HashMap<String, Object>();
        params.put(Common.DELSTATUS, DelStatus.NODEL);
        params.put(Common.ID, idsList);
        List<Refundorder> refundorderList = refundorderService.getByParams(params);
        if (refundorderList == null || refundorderList.size() == 0) {
            return JsonUtil.toJson(CommonInfoUtil.NULLDATA, "空数据");
        }
        for (Refundorder refundorder : refundorderList) {
            Map<String, Object> prams = new HashMap<String, Object>();
            prams.put(Common.DELSTATUS, DelStatus.NODEL);
            prams.put("orderNo", refundorder.getOrderNo());
            Userorder userorder = userorderService.getByParam(prams);
            if (userorder == null) {
                return JsonUtil.toJson(CommonInfoUtil.NULLDATA, "原订单信息不存在");
            }

            if (applyStatus == 1) {
                userorder.setRefund(1);
            } else if (applyStatus == -1) {
                userorder.setStatus(4);
                userorder.setRefund(-1);
            }
            refundorder.setApplyStatus(applyStatus);
            if (reason != null && reason.length() > 0) {
                refundorder.setRefuseReason(reason);
            }
            userorder.setGmtModify(new Date());
            userorderService.saveOrUpdate(userorder);
            refundorder.setGmtApply(new Date());
            refundorderService.saveOrUpdate(refundorder);
        }
        return JsonUtil.toJson(CommonInfoUtil.SUCCESS, "操作完成");//jsonObject	json对象
    }

    /**
     * I-86
     * 处理退款订单
     *
     * @param modelMap
     * @param request
     * @return
     * @throws BusinessException
     * @throws IOException
     */
    @ResponseBody
    @RequestMapping("sysUserGetInfo/disposeRefundorder")
    public String disposeRefundorder(ModelMap modelMap, HttpServletRequest request) throws BusinessException, IOException {
        Long id = getLong("id", request);
        Integer takeStatus = optInteger("takeStatus", request);
        Refundorder refundorder = refundorderService.get(id);
        if (refundorder == null) {
            return JsonUtil.toJson(CommonInfoUtil.NULLDATA, "退款订单不存在");
        }
        Map<String, Object> prams = new HashMap<String, Object>();
        prams.put(Common.DELSTATUS, DelStatus.NODEL);
        Map<String, Object> searchParams = new HashMap<String, Object>();
        searchParams.put("orderNos", refundorder.getOrderNo());
        Yibaopayment yibaopayment = yibaopaymentService.getByParam(prams, searchParams, null);
        if (yibaopayment == null) {
            return JsonUtil.toJson(CommonInfoUtil.NULLDATA, "订单流水信息不存在");
        }
        prams = new HashMap<String, Object>();
        prams.put(Common.DELSTATUS, DelStatus.NODEL);
        prams.put("orderNo", refundorder.getOrderNo());
        Userorder userorder = userorderService.getByParam(prams);
        if (userorder == null) {
            return JsonUtil.toJson(CommonInfoUtil.NULLDATA, "订单不存在");
        }
        if (userorder.getMerchantStatus() == 1 || userorder.getPlatformStatus() == 1) {
            return JsonUtil.toJson(CommonInfoUtil.NOPERMISSIONS, "订单已提现无法退款");
        }
        prams = new HashMap<String, Object>();
        prams.put(Common.DELSTATUS, DelStatus.NODEL);
        prams.put("orderNo", refundorder.getOrderNo());
        Yibaodivide yibaodivide = yibaodivideService.getByParam(prams);
        if (yibaodivide == null) {
            Divideresult divideresult = YibaopayUtil.yibaoDivide(yibaopayment, userorder);
            if (divideresult != null && divideresult.getCode().equals("OPR00000")) {
                yibaodivide = new Yibaodivide(divideresult.getStatus(), divideresult.getOrderId(), refundorder.getOrderNo(), divideresult.getUniqueOrderNo(),
                        divideresult.getDivideRequestId(), divideresult.getDivideDetail());
                yibaodivideService.saveOrUpdate(yibaodivide);
            } else {
                return JsonUtil.toJson(CommonInfoUtil.DATAERROR, divideresult.getMessage(), divideresult);
            }
        } else {
            JSONObject jsonObject = YibaopayUtil.getYibaoDivide(yibaodivide.getOrderId(), yibaodivide.getUniqueOrderNo(), yibaodivide.getDivideRequestId());
            if (jsonObject != null && !jsonObject.getString("code").equals("OPR00000")) {
                return JsonUtil.toJson(CommonInfoUtil.DATAERROR, jsonObject.getString("message"), jsonObject);
            }
        }
        prams = new HashMap<String, Object>();
        prams.put(Common.DELSTATUS, DelStatus.NODEL);
        prams.put("orderNo", refundorder.getOrderNo());
        Yibaorefund yibaorefund = yibaorefundService.getByParam(prams);
        if (yibaorefund == null) {
            Refundresult refundresult = YibaopayUtil.yibaoRefund(yibaodivide, userorder, yibaopayment);
            if (refundresult != null && refundresult.getCode().equals("OPR00000")) {
                yibaorefund = new Yibaorefund(refundresult, yibaopayment, userorder.getOrderNo());
                yibaorefundService.saveOrUpdate(yibaorefund);
            } else {
                return JsonUtil.toJson(CommonInfoUtil.DATAERROR, refundresult.getMessage(), refundresult);
            }
        } else {
            JSONObject data = YibaopayUtil.yibaoGetRefund(yibaorefund.getOrderId(), yibaorefund.getUniqueRefundNo(), yibaorefund.getRefundOrderNo());
            if (data != null && !data.getString("code").equals("OPR00000")) {
                return JsonUtil.toJson(CommonInfoUtil.DATAERROR, data.getString("message"), data);
            }
        }
        refundorder.setTakeStatus(takeStatus);
        refundorder.setStatus(0);
        refundorderService.saveOrUpdate(refundorder);
        return JsonUtil.toJson(CommonInfoUtil.SUCCESS, "操作完成");
    }

    /**
     * 查询所有退款订单
     *
     * @param modelMap
     * @param session
     * @return
     */
    @ResponseBody
    @RequestMapping("getAllRefundorder")
    public String getAllRefundorder(ModelMap modelMap, HttpServletRequest request) throws BusinessException {
        List<Refundorder> refundorderList = refundorderService.getByParams(null);
        if (refundorderList == null || refundorderList.size() == 0) {
            return JsonUtil.toJson(CommonInfoUtil.NULLDATA, "空数据");
        }
        return JsonUtil.toJson(CommonInfoUtil.SUCCESS, "操作完成", refundorderList);//jsonObjectList	json对象集合
    }


    /**
     * 导出售后订单  TODO
     *
     * @param param
     * @param request
     * @param response
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "/exportRefundOrder", produces = "application/json")
    public void exportRefundOrder(@RequestBody Map<String, Object> param, HttpServletRequest request,
                                  HttpServletResponse response) throws Exception {
        //根据条件查询全部数据,不分页
        List<ExportRefundOrderVO> exportOrderList = refundorderService.listExportOrderDatas(param);
        if (CollectionUtils.isEmpty(exportOrderList)) {
            throw new BusinessException(-1, "没有要导出的数据");
        }

        try {
            String fileName = "售后订单" + DateUtil.simpyMdHHmmss.format(new Date());
            ExportParams exportParams = new ExportParams(null, "售后订单", ExcelType.XSSF);
            exportParams.setStyle(ExcelStyleUtil.class);

            EasyPoiUtil.exportExcel(fileName, exportParams, ExportRefundOrderVO.class, exportOrderList, request, response);
        } catch (Exception ex) {
            throw new BusinessException(-1, "导出数据失败");
        }
    }
}
